module Graphics.ZSorter;
private import Graphics.IGraphics;


public class ZSorter{
	private IDrawingEntry[] sortBuffer;
	private bool  sorted = false;
	 private bool sortEnable = true;
	private int cnt =    0;
	private const int MAX = 8192;
	

	public this(){
		sortBuffer = new IDrawingEntry[ MAX ];
		cnt = 0;
	} //

	public bool add( IDrawingEntry s ){
		if( cnt > MAX )return false;
		sortBuffer[cnt++] = s;
		sorted = false;
		return true;
	} //

	public void sort(){
		if(!sortEnable)return;
		int  i , j ;
		 for ( i = 0 ; i < cnt ; i++ ) {
		  for ( j = cnt - 1 ; j > i ; j-- ) {
			if( sortBuffer[j].z > sortBuffer[j-1].z ) {
				int jj = j-1;
				IDrawingEntry tmp = sortBuffer[j];
				sortBuffer[j]	= sortBuffer[jj];
				sortBuffer[jj]  = tmp;
			}
		  }
		 }
		sorted=true;
	}

	public void clear(){
		for( int i = cnt - 1 ; i >= 0 ; i-- )sortBuffer[i] = null;//.clear();
		sorted = false;
		cnt=0;
	}

	public bool draw( IGraphics g ){
		if (cnt < 1) return true;
		sort();
		for( int i = cnt - 1 ; i >= 0 ; i-- )
			sortBuffer[i].draw( g );
		clear();
		return true;
	}
/*
	public bool draw( IGraphics g , float from , float to , bool clFlag = false ){
		if (cnt < 1) return true;
		int i;
		if ( sortEnable ) {
		 if( !sorted )sort();
			for ( i = cnt-1 ; i >= 0 ; i-- ) {
			  if ( sortBuffer[i].getZ() > from ) continue;
			  if ( sortBuffer[i].getZ() < to   ) break;
			  sortBuffer[i].draw( g );
			}
		}else{
			for ( i = cnt-1 ; i >= 0 ; i-- ) {
			  if ( sortBuffer[i].getZ() > from ) continue;
			  if ( sortBuffer[i].getZ() < to   ) continue;
			  sortBuffer[i].draw( g );
			}
		}
		if(clFlag)clear();
	} //
//*/

} //